package com.example.demo.service.impl;


import com.example.demo.dao.userDAO;
import com.example.demo.model.Result;
import com.example.demo.model.user;
import com.example.demo.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


@Component
public class userServiceImpl implements userService {

    @Autowired
    private userDAO userDAO;

    @Override
    public Result<user> register(String userName, String pwd, int age, String phone, double money) {
        Result<user> result = new Result<>();

        if (StringUtils.isEmpty(userName)) {
            result.setCode("600");
            result.setMessage("用户名不能为空");
            return result;
        }
        if (StringUtils.isEmpty(pwd)) {
            result.setCode("601");
            result.setMessage("密码不能为空");
            return result;
        }

        user user = userDAO.findByUserName(userName);
        if (user!=null){
            result.setCode("602");
            result.setMessage("用户名已经存在");
            return result;
        }

        user user1 = new user();
        user1.setUsername(userName);
        user1.setPassword(pwd);
        user1.setAge(age);
        user1.setPhone(phone);
        user1.setMoney(money);
        userDAO.add(user1);

        result.setSuccess(true);

        result.setData(user1);

        return result;
    }

    @Override
    public Result<user> login(String userName, String pwd) {

        Result<user> result = new Result<>();

        if (StringUtils.isEmpty(userName)) {
            result.setCode("600");
            result.setMessage("用户名不能为空");
            return result;
        }
        if (StringUtils.isEmpty(pwd)) {
            result.setCode("601");
            result.setMessage("密码不能为空");
            return result;
        }

        user user = userDAO.findByUserName(userName);
        if (user==null){
            result.setCode("602");
            result.setMessage("用户名不存在");
            return result;
        }


        if (!(pwd.equals(user.getPassword()))){
            result.setCode("603");
            result.setMessage("密码不对");
            return result;
        }


        result.setSuccess(true);

        result.setData(user);

        return result;
    }

    @Override
    public int add(user user) {

        return userDAO.add(user);
    }

    @Override
    public int update(user user) {
        return userDAO.update(user);
    }

    @Override
    public int delete(int id) {
        return userDAO.delete(id);
    }

    @Override
    public user findByUserName(String username) {
        return userDAO.findByUserName(username);
    }

    @Override
    public user findByUserId(int id) {
        if (id >0){
            return userDAO.findByUserId(id);
        }
        return null;
    }

}
